import React from 'react';
import { Table, Input, Popconfirm, Form, Button, Typography, TreeSelect, message, Spin } from 'antd';
import { history } from 'umi'
import { DividerContainer } from '@/molecules';
import { FileUploadPublic } from '@/containers';
import authHelper from '@/utils/auth/helper';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getOrganizationTree } from '@/services/Organization/orgmanage';
import { Icon, AntIcon } from '../../../components';
import { getDeclareSetList, addDeclareSet, updateDeclareSet, deleteDeclareSet } from '../../service';
import { transformPublicFileList } from '../../../utils';
import styles from './index.less';

const { Paragraph } = Typography;
const { TreeNode } = TreeSelect;
const { checkCode } = authHelper;

const EditableContext = React.createContext();

const EditItem = props => {
    const { editing, dataIndex, title, record, index, children, orgList, disabledList, ...restProps } = props;
    const context = React.useContext(EditableContext);
    const { form } = context;
    const { getFieldDecorator, getFieldValue } = form;

    const getItem = () => {
        if (dataIndex === 'organizationCodes') {
            if (record?.type === 0) {
                return '默认（未特殊指定时，默认采用此设置）';
            }
            return (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                        rules: [
                            {
                                required: true,
                                message: `请选择${title}`
                            }
                        ],
                        initialValue: record && record[dataIndex] ? record[dataIndex].split(',') : undefined
                    })(
                        <TreeSelect
                            dropdownClassName={styles.treeSelectDropDown}
                            treeCheckable
                            dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                            placeholder={`请选择${title}`}
                            allowClear
                            maxTagCount={1}
                            style={{ width: '100%' }}
                            treeNodeFilterProp="title"
                            getPopupContainer={trigger => trigger.parentElement}
                        >
                            {orgList.map(item => (
                                <TreeNode
                                    value={item.organizationCode}
                                    title={item.organizationName}
                                    key={item.organizationCode}
                                    disabled={
                                        disabledList?.includes(item.organizationCode) &&
                                        !form.getFieldValue(dataIndex)?.includes(item.organizationCode)
                                    }
                                />
                            ))}
                        </TreeSelect>
                    )}
                </Form.Item>
            );
        }
        if (dataIndex === 'clause') {
            return (
                <Form.Item style={{ margin: 0, width: 180 }}>
                    {getFieldDecorator(dataIndex, {
                        initialValue:
                            record && record[dataIndex]
                                ? transformPublicFileList([record[dataIndex]])
                                : { allFileList: [] }
                    })(
                        <FileUploadPublic
                            checkFileSizeMsg="文件大小不能超过50MB！"
                            checkFileSize={50}
                            checkFileType="DOC,DOCX,PDF,JPG,JPEG"
                            checkFileTypeMsg="附件格式不合规，请确认！"
                        >
                            <Button
                                type="link"
                                icon="upload"
                                disabled={getFieldValue(dataIndex)?.allFileList?.length > 0}
                            ></Button>
                        </FileUploadPublic>
                    )}
                </Form.Item>
            );
        }

        return (
            <Form.Item style={{ margin: 0 }}>
                {getFieldDecorator(dataIndex, {
                    rules: [
                        {
                            required: true,
                            message: `请输入${title}`,
                            whitespace: true
                        }
                    ],
                    initialValue: (record && record[dataIndex]) || ''
                })(
                    <Input.TextArea
                        placeholder={`请输入${title}`}
                        autoSize={{ minRows: 3, maxRows: 6 }}
                        maxLength={500}
                        style={{ width: '100%' }}
                    />
                )}
            </Form.Item>
        );
    };

    const renderCell = () => {
        if (editing) {
            return <td {...restProps}>{getItem()}</td>;
        }

        return <td {...restProps}>{children}</td>;
    };

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
};

const DeclareTable = ({ form: tempForm }) => {
    const { data: orgList } = useRequest(() => getOrganizationTree({ showTreeFlag: 0, organizationTypes: [1, 2] }), {
        initialData: [],
        ...defaultFormatResult
    });

    const gradeMap = React.useMemo(() => {
        if (!orgList) {
            return {};
        }
        const obj = {};
        orgList.forEach(item => {
            obj[item.organizationCode] = item;
        });
        return obj;
    }, [orgList]);

    const [editingKey, setEditingKey] = React.useState('');
    const [disabledList, setDisabledList] = React.useState([]);

    // 获取声明设置列表
    const { data, loading, run: fetchDeclareList, mutate: setData } = useRequest(getDeclareSetList, {
        manual: true,
        initialData: [],
        ...defaultFormatResult,
        onSuccess: () => {
            setEditingKey('');
        }
    });

    const setFinalDisabledList = key => {
        const arr = [];
        data.forEach(({ id, organizationCodes }) => {
            if (key === id) {
                return;
            }
            if (organizationCodes) {
                organizationCodes.split(',').forEach(item => {
                    arr.push(item);
                });
            }
        });
        setDisabledList(arr || []);
    };

    // 新增声明设置
    const { run: addDeclare, loading: addLoading } = useRequest(addDeclareSet, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchDeclareList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    // 更新声明设置
    const { run: updateDeclare, loading: updateLoading } = useRequest(updateDeclareSet, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchDeclareList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    // 删除声明设置
    const { run: delDeclare, loading: deleteLoading } = useRequest(deleteDeclareSet, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchDeclareList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    const isEditing = record => record.id === editingKey;

    const handleSave = (form, key) => {
        tempForm.validateFields((error, row) => {
            if (error) {
                return;
            }
            const { clause, organizationCodes = [] } = row;
            const finalParams = {
                ...row,
                clause: clause?.allFileList?.[0]?.url || '',
                organizationCodes: organizationCodes && organizationCodes.length > 0 ? organizationCodes.join(',') : '',
                organizationNames: organizationCodes?.map(o => gradeMap[o].organizationName).join(',') || ''
            };

            if (`${key}`.startsWith('add')) {
                addDeclare(finalParams);
            } else {
                updateDeclare({
                    ...finalParams,
                    id: key
                });
            }
        });
    };

    const handleCancel = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (`${key}`.startsWith('add')) {
            newData.splice(index, 1);
            setData(newData);
            setEditingKey('');
        } else {
            setEditingKey('');
        }
    };

    const handleEdit = key => {
        setFinalDisabledList(key);
        setEditingKey(key);
    };

    const handleDelete = key => {
        delDeclare(key);
    };

    const handleAdd = () => {
        setFinalDisabledList();
        const newData = [...data];
        const tempKey = `add${new Date().getTime().toString()}`;
        newData.push({
            id: tempKey,
            organizationCodes: '',
            statementContent: '',
            clause: null
        });
        setData(newData);
        setEditingKey(tempKey);
    };

    React.useEffect(() => {
        fetchDeclareList();
    }, []);

    const handlePreview = (record, editing) => {
        let canPass = true;
        let param = {};
        if (editing) {
            tempForm.validateFields((error, row) => {
                if (error) {
                    canPass = false;
                    return;
                }
                param = row;
            });
        } else {
            const newData = [...data];
            const index = newData.findIndex(item => record.id === item.id);
            if (index > -1) {
                param = newData[index];
            }
        }
        if (!canPass) {
            return;
        }
        const { clause, statementContent } = param;
        const finalParam = {
            title: statementContent,
            file: clause?.allFileList ? clause?.allFileList?.[0]?.url : clause
        };
        localStorage.setItem(
            'localDeclare',
            JSON.stringify({
                [record.id]: finalParam
            })
        );
        history.push({
            pathname: '/office/personnelManagement/recruitment/setting/declare',
            state: { tabRoute: true },
            query: {
                id: record.id
            }
        });
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 80,
            render: (text, record, index) => index + 1
        },
        {
            title: '适用范围',
            dataIndex: 'organizationCodes',
            width: '25%',
            editable: true,
            render: (_text, record) => {
                if (record?.type === 0) {
                    return '默认（未特殊指定时，默认采用此设置）';
                }
                return (
                    <Paragraph ellipsis={{ rows: 3, expandable: true }} style={{ marginBottom: 0 }}>
                        {record?.organizationNames?.replace(/,/g, '、')}
                    </Paragraph>
                );
            }
        },
        {
            title: '声明内容',
            dataIndex: 'statementContent',
            editable: true,
            render: text => (
                <Paragraph ellipsis={{ rows: 3, expandable: true }} style={{ marginBottom: 0 }}>
                    {text}
                </Paragraph>
            )
        },
        {
            title: '法律条款',
            dataIndex: 'clause',
            width: 180,
            editable: true,
            render: text => {
                if (text) {
                    return (
                        <div className={styles.fileUpload}>
                            <FileUploadPublic value={transformPublicFileList([text])} disabled />
                        </div>
                    );
                }
                return '无';
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 160,
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <DividerContainer>
                        {/* <Icon title="查看" type="yuanshijianli" onClick={() => handlePreview(record, true)} /> */}
                        <AntIcon
                            title="查看"
                            type="eye"
                            onClick={() => handlePreview(record, true)}
                            style={{ marginBottom: 6 }}
                        />
                        <EditableContext.Consumer>
                            {form => <Icon title="保存" type="confirm_o" onClick={() => handleSave(form, record.id)} />}
                        </EditableContext.Consumer>
                        <Icon title="取消" type="cancel_o" onClick={() => handleCancel(record.id)} />
                    </DividerContainer>
                ) : (
                    <DividerContainer>
                        {/* <Icon
                            title="查看"
                            disabled={editingKey !== ''}
                            type="yuanshijianli"
                            onClick={() => handlePreview(record, false)}
                        /> */}
                        <AntIcon
                            title="查看"
                            type="eye"
                            disabled={editingKey !== ''}
                            onClick={() => handlePreview(record, false)}
                            style={{ marginBottom: 6 }}
                        />
                        {checkCode('office:recruitment:setting:interview:register:declare:update') && (
                            <Icon
                                title="编辑"
                                disabled={editingKey !== ''}
                                type="listfunction_edit_icon_default"
                                onClick={() => handleEdit(record.id)}
                            />
                        )}
                        {checkCode('office:recruitment:setting:interview:register:declare:delete') && (
                            <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
                                <Icon
                                    title="删除"
                                    disabled={editingKey !== '' || record?.type === 0}
                                    type="listfunction_delete_icon_default"
                                    onClick={() => {}}
                                />
                            </Popconfirm>
                        )}
                    </DividerContainer>
                );
            }
        }
    ];

    const realColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                orgList,
                disabledList,
                editing: isEditing(record)
            })
        };
    });

    const components = {
        body: {
            cell: EditItem
        }
    };

    return (
        <EditableContext.Provider value={{ form: tempForm }}>
            <Spin spinning={loading || addLoading || updateLoading || deleteLoading}>
                <Table
                    rowKey="id"
                    bordered={false}
                    components={components}
                    dataSource={data}
                    columns={realColumns}
                    rowClassName={styles.editableRow}
                    pagination={false}
                />
                {checkCode('office:recruitment:setting:interview:register:declare:create') && (
                    <Button
                        type="dashed"
                        icon="plus"
                        block
                        disabled={editingKey !== ''}
                        style={{ marginTop: 12 }}
                        onClick={handleAdd}
                    >
                        添加
                    </Button>
                )}
            </Spin>
        </EditableContext.Provider>
    );
};

export default Form.create()(DeclareTable);
